package com.hardson.toolkit.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

public class IOUtil {

	public static int copy(InputStream input, OutputStream output) throws IOException {
		return IOUtils.copy(input, output);
	}

	public static long copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
		return IOUtils.copy(input, output, bufferSize);
	}

	public static long copyLarge(InputStream input, OutputStream output, byte[] buf) throws IOException {
		return IOUtils.copyLarge(input, output, buf);
	}

	/**
	 * 复制流中的字节数据，并反馈复制进程
	 *
	 * @param input
	 * @param output
	 * @param process
	 * @return
	 * @throws IOException
	 */
	public static int copy(InputStream input, OutputStream output, IOProcess process) throws IOException {
		return copy(input, output, 1024 * 4, process);
	}

	/**
	 * 按指定的单位字节数组大小，复制流中的字节数据，并反馈复制进程
	 *
	 * @param input
	 * @param output
	 * @param buffersize
	 * @param process
	 * @return
	 * @throws IOException
	 */
	public static int copy(InputStream input, OutputStream output, int buffersize, IOProcess process)
			throws IOException {
		int count = 0;
		int len;
		byte[] buffer = new byte[buffersize];
		for (; (len = input.read(buffer)) != -1;) {
			output.write(buffer, 0, len);
			count += len;
			if (process != null) {
				process.process(len);
				if (process.isCancel()) {
					break;
				}
			}
		}
		return count;
	}
}
